package com.rongji.cms.tools.common.exception;

import cn.hutool.http.HttpStatus;
import com.rongji.cms.tools.common.enums.CommonResultCode;
import com.rongji.cms.tools.common.vo.ResultVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * 全局异常处理程序
 *
 * @author yang
 * @date 2022/6/13 14:38
 * @description 统一异常处理，这里处理基本的异常，比如空指针等，和其他类异常
 * 每个业务模块继承此类，处理自己模块的业务异常
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(value = NullPointerException.class)
    public ResultVO nullPointerExceptionHandler(NullPointerException e) {
        log.error(e.getMessage(), e);
        log.error("错误原因：");
        log.error("_> {}", e.getMessage());
        log.error("=============================错误打印完毕=============================");
        return new ResultVO(CommonResultCode.INTERNAL_SERVER_ERROR.getCode(), CommonResultCode.INTERNAL_SERVER_ERROR.getMsg(), e.getMessage());
    }


    /**
     * 自动注入异常
     *
     * @param e
     * @return
     */
    @ExceptionHandler(value = ServiceException.class)
    public ResultVO ServiceExceptionHandler(ServiceException e) {
        log.error(e.getMessage(), e);
        log.error("错误原因：");
        log.error("_> {}", e.getMessage());
        log.error("=============================错误打印完毕=============================");
        return new ResultVO(HttpStatus.HTTP_UNAUTHORIZED, "自动注入异常 => " + e.getMessage(), e.getMessage());
    }

    //    其他异常
    @ExceptionHandler(value = Exception.class)
    public ResultVO exceptionHandler(Exception e) {
        log.error(e.getMessage(), e);
        log.error("错误原因：");
        log.error("_> {}", e.getMessage());
        log.error("=============================错误打印完毕=============================");
        return new ResultVO(CommonResultCode.INTERNAL_SERVER_ERROR.getCode(), CommonResultCode.INTERNAL_SERVER_ERROR.getMsg(), e.getMessage());
    }


}
